<?php
namespace app\admin\controller;

class Admin extends Base
{
    private $tn = 'admin';

    public function index()
    {
        if (isset($this->get['page']) && isset($this->get['limit'])) {
            $where = ['id' => ['>', 1]];
            if (isset($this->get['role'])) {
                $where['role'] = $this->get['role'];
            }
            $list = db($this->tn)->field(true)->where($where)->page($this->get['page'])->limit($this->get['limit'])->select();
            foreach ($list as $k => $v) {
                $list[$k]['role']        = get_field('admin_role', $v['role']);
                $list[$k]['create_time'] = date('Y-m-d H:i:s', $v['create_time']);
            }
            $count = db($this->tn)->where($where)->count();
            $this->returnAPI('', 0, $list, ['count' => $count, 'limit' => $this->get['limit']]);
        }
        return $this->fetch('', ['roles' => ['' => '用户角色'] + db('role')->column('name', 'id')]);
    }

    public function edit($id = 0)
    {
        $model = model($this->tn);
        if ($this->post) {
            if ($id) {
                $model = $model->get($id);
                if (is_null($model)) {
                    $this->returnAPI('信息有误，请稍后重试');
                }
            }
            $result = $model->validate($this->tn)->allowField(true)->save($this->post);
            if ($result !== false) {
                $this->returnAPI('操作成功', 0);
            }
            $this->returnAPI($model->getError());
        }
        $model = $model->get($id);
        if (is_null($model)) {
            $data = $this->table_fields($this->tn);
        } else {
            $data = $model->getData();
        }
        return $this->fetch('', [
            'data'  => $data,
            'roles' => ['' => '用户角色'] + db('role')->column('name', 'id'),
        ]);
    }
}
